function testFN(fn, args) { //测试
	console.log(fn(...args));
}

const styleObj2Str = (obj) => { //{zIndex:100,color:"#FFF"} =>'z-index:100;color:#FFF'
	let result = '';
	for (let key in obj) {
		let tempKey = '';

		for (let i = 0; i < key.length; i++) {
			// tempKey = tempKey + ((isNaN(key[i])&&(key[i] == key[i].toUpperCase()))? ("-"+key[i].toLowerCase()):key[i]);
			tempKey = tempKey + ((/[A-Z]/.test(key[i])) ? ("-" + key[i].toLowerCase()) : key[i]);
		};
		result += `${tempKey}:${obj[key]};`
	};
	return result
};

/**
 * 表格时间格式化
 */
function formatDate(cellValue) {
	if (cellValue == null || cellValue == "") return "";
	var date = new Date(cellValue)
	var year = date.getFullYear()
	var month = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1
	var day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()
	var hours = date.getHours() < 10 ? '0' + date.getHours() : date.getHours()
	var minutes = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()
	var seconds = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()
	return year + '-' + month + '-' + day + ' ' + hours + ':' + minutes + ':' + seconds
}

const formatTime = date => { //date=>'2022/07/13 21:50:55'
	const year = date.getFullYear()
	const month = date.getMonth() + 1
	const day = date.getDate()
	const hour = date.getHours()
	const minute = date.getMinutes()
	const second = date.getSeconds()

	return `${[year, month, day].map(formatNumber).join('/')}-${[hour, minute, second].map(formatNumber).join(':')}`
}

const formatNumber = n => n.toString().padStart(2, "0"); //1=>01

const Adapt = function(e) { //微信小程序获取当前屏幕大小,注意:获取到的是px而非rpx
	let imageSize = {}
	let imgH = '',
		topT = ''
	uni.getSystemInfo({
		success: function(res) {
			console.log(res)
			let ratio = res.windowWidth / e.detail.width,
				imgW = res.windowWidth
			if (res.windowWidth > e.detail.width) {
				imgH = e.detail.height / ratio;
			} else {
				imgH = e.detail.height * ratio;
			}
			if (res.windowHeight > imgH) {
				let t = res.windowHeight - imgH

				topT = t / 2
				console.log(topT)
			}
			imageSize = {
				imageHeight: imgH,
				imageWidth: imgW,
				topT: topT
			}
		}
	})
	return imageSize
}

function getAge(strAge) { //根据出生日期 计算岁数
	if (!strAge) return '';
	//2021-06-20 09:23:12
	strAge = strAge.length == 10 ? strAge : strAge.slice(0, 10);
	var birArr = strAge.split("-");
	var birYear = birArr[0];
	var birMonth = birArr[1];
	var birDay = birArr[2];

	d = new Date();
	var nowYear = d.getFullYear();
	var nowMonth = d.getMonth() + 1; //记得加1
	var nowDay = d.getDate();
	var returnAge;

	if (birArr == null) {
		return false
	};
	var d = new Date(birYear, birMonth - 1, birDay);
	if (d.getFullYear() == birYear && (d.getMonth() + 1) == birMonth && d.getDate() == birDay) {
		if (nowYear == birYear) {
			returnAge = 0; // 
		} else {
			var ageDiff = nowYear - birYear; // 
			if (ageDiff > 0) {
				if (nowMonth == birMonth) {
					var dayDiff = nowDay - birDay; // 
					if (dayDiff < 0) {
						returnAge = ageDiff - 1;
					} else {
						returnAge = ageDiff;
					}
				} else {
					var monthDiff = nowMonth - birMonth; // 
					if (monthDiff < 0) {
						returnAge = ageDiff - 1;
					} else {
						returnAge = ageDiff;
					}
				}
			} else {
				return "出生日期晚于今天，数据有误"; //返回-1 表示出生日期输入错误 晚于今天
			}
		}
		return returnAge;
	} else {
		return ("输入的日期格式错误！");
	}
}

function num2weekDay(num, str = `周`) { //数字转周几
	let temp = "日一二三四五六";
	return temp[num] ? `${str}${temp[num]}` : '';
}

const getDateToNewData = (diffValue) => { //根据时间 计算距离当前时间
	if (diffValue) {
		return ""
	};
	//2021-06-20 09:23:12
	//如果时间格式是正确的，那下面这一步转化时间格式就可以不用了
	var dateBegin = new Date(diffValue.replace(/-/g, "/")); //将-转化为/，使用new Date
	var dateEnd = new Date(); //获取当前时间
	var dateDiff = dateEnd.getTime() - dateBegin.getTime(); //时间差的毫秒数
	var monthC = Math.floor(dateDiff / (24 * 3600 * 1000 * 30)); //计算出相差月数
	var leaveMon = dateDiff % (24 * 3600 * 1000 * 30); //计算月数后剩余的毫秒数
	var weekC = Math.floor(leaveMon / (24 * 3600 * 1000 * 7)); //计算出相差星期数
	var leaveWeek = leaveMon % (24 * 3600 * 1000 * 7); //计算星期数剩余的毫秒数
	var dayC = Math.floor(leaveWeek / (24 * 3600 * 1000)); //计算出相差天数
	var leave1 = leaveWeek % (24 * 3600 * 1000) //计算天数后剩余的毫秒数
	var hours = Math.floor(leave1 / (3600 * 1000)) //计算出小时数
	//计算相差分钟数
	var leave2 = leave1 % (3600 * 1000) //计算小时数后剩余的毫秒数
	var minutes = Math.floor(leave2 / (60 * 1000)) //计算相差分钟数
	//计算相差秒数
	var leave3 = leave2 % (60 * 1000) //计算分钟数后剩余的毫秒数
	var seconds = Math.round(leave3 / 1000);
	var timesString = '';
	if (monthC != 0) {
		if (monthC > 6) {
			var timearr = diffValue.substring(0, 10).split("-");
			var timestrS = "" + timearr[0] + "年" + timearr[1] + "月" + timearr[2] + "日"
			timesString = timestrS
		} else if (monthC == 6) {
			timesString = '半年前'
		} else if (monthC < 6) {
			timesString = monthC + '月之前'
		}
	} else if (monthC == 0 && weekC != 0) {
		timesString = weekC + '周之前';
	} else if (weekC == 0 && dayC != 0) {
		timesString = dayC + '天之前';
	} else if (dayC == 0 && hours != 0) {
		timesString = hours + '小时之前';
	} else if (hours == 0 && minutes != 0) {
		timesString = minutes + '分钟之前';
	}
	return timesString;
}

function getAstro(date) { //判断星座
	//2021-06-20 09:23:12
	var date2 = new Date(date);
	var month = date2.getMonth() + 1
	var day = date2.getDate()
	// var s="魔羯⽔瓶双鱼牡⽺⾦⽜双⼦巨蟹狮⼦处⼥天秤天蝎射⼿魔羯";
	var s = "摩羯水瓶双鱼白羊金牛双子巨蟹狮子处女天枰天蝎射手摩羯";
	var arr = [20, 19, 21, 21, 21, 22, 23, 23, 23, 23, 22, 22];
	return s.substr(month * 2 - (day < arr[month - 1] ? 2 : 0), 2);
}

function easyToast(title, icon = "none", gref = uni) { //微信小程序提示
	return gref.showToast({
		icon,
		title
	});
}

function throttle(fn, interval) { //函数节流
	var enterTime = 0; //触发的时间
	var gapTime = interval || 300; //间隔时间，如果interval不传，则默认300ms
	return function() {
		var context = this;
		var backTime = new Date(); //第一次函数return即触发的时间
		if (backTime - enterTime > gapTime) {
			fn.call(context, ...arguments);
			enterTime = backTime; //赋值给第一次触发的时间，这样就保存了第二次触发的时间
		}
	};
}

function debounce(fn, interval) { //函数防抖
	var timer;
	var gapTime = interval || 1000; //间隔时间，如果interval不传，则默认1000ms
	return function() {
		clearTimeout(timer);
		var context = this;
		var args = arguments; //保存此处的arguments，因为setTimeout是全局的，arguments不是防抖函数需要的。
		timer = setTimeout(function() {
			fn.call(context, ...args);
		}, gapTime);
	};
}

function isRGBFormat(str) { //判断是否是rgb格式
	let rgbRegex = /rgba\([^\)]+\)|rgb\([^\)]+\)/i;
	return rgbRegex.test(str);
}

function isHexFormat(str) { // 判断是否是hex格式
	let hexRegex = /^#[0-9A-Fa-f]{6,8}$/;
	return hexRegex.test(str);
}

function rgbToHex(red, green, blue, opacity) { //rgb转Hex
	let hexRed = (+red).toString(16).padStart(2, '0');
	let hexGreen = (+green).toString(16).padStart(2, '0');
	let hexBlue = (+blue).toString(16).padStart(2, '0');
	let a = (+opacity).toString(16).padStart(2, '0');
	return `#${hexRed}${hexGreen}${hexBlue}${a}`;
}

function hexToRgb(hex) { //hex转rgb
	// 去除#号
	var color = hex.replace("#", "");

	// 分割成红、绿、蓝三部分的十六进制字符串
	var red = parseInt(color.substring(0, 2), 16);
	var green = parseInt(color.substring(2, 4), 16);
	var blue = parseInt(color.substring(4, 6), 16);
	var alpha = parseInt(color.substring(6, 8), 16);
	if (isNaN(alpha)) alpha = 255;
	return {
		r: red,
		g: green,
		b: blue,
		a: alpha / 255
	};
}

function getRGBAValue(color) { //获取rgb值
	let str = color.toLocaleLowerCase().replace(/(rgba)|(rgb)/, '');
	return str.slice(1, -1).split(",").map((e, i) => (i == 3 ? parseInt(255 * e) : +e));
}

/**
 * param 将要转为URL参数字符串的对象
 * key URL参数字符串的前缀
 * encode true/false 是否进行URL编码,默认为true
 * idx ,循环第几次，用&拼接
 * return URL参数字符串
 */
var urlEncode = (param, idx, key, encode) => {
	if (param == null) return '';
	var paramStr = '';
	var t = typeof(param);
	if (t == 'string' || t == 'number' || t == 'boolean') {
		var one_is = idx < 3 ? '?' : '&';
		paramStr += one_is + key + '=' + ((encode == null || encode) ? encodeURIComponent(param) : param);
	} else {
		for (var i in param) {
			var k = key == null ? i : key + (param instanceof Array ? '[' + i + ']' : '.' + i);
			idx++
			paramStr += urlEncode(param[i], idx, k, encode);
		}
	}
	return paramStr;
}

var deCodeUrl = (params) => { //enCode=>deCode
	if (undefined === params || null === params) {
		return '';
	};
	let d = decodeURIComponent;
	return (typeof params === "object") ? JSON.parse(d(JSON.stringify(params))) : d(params);
}

function rpx2px(rpx, deviceWidth) { //rpx转px
	deviceWidth = deviceWidth ? deviceWidth : uni.getSystemInfoSync().windowWidth; //获取设备屏幕宽度
	let px = (deviceWidth / 750) * Number(rpx)
	return Math.floor(px);
}

function px2rpx(px, deviceWidth) { //px转rpx
	// deviceWidth = deviceWidth?deviceWidth: uni.getSystemInfoSync().windowWidth; //获取设备屏幕宽度
	let rpx = (750 / deviceWidth) * Number(px)
	return Math.floor(rpx);
}

function vh2px(vhValue) {
	// 获取视口的高度
	const viewportHeight = Math.max(document.documentElement.clientHeight || 0, window.innerHeight || 0);
	// 将 vh 转换为像素
	const pxValue = (vhValue * viewportHeight) / 100;
	return (pxValue); // 输出转换后的像素值
}

function editStr(oldStr, index, str) { //编辑STR
	return oldStr.slice(0, index) + str + oldStr.slice(index);
}

function myTypeOf(obj) { //判断数据类型
	return Object.prototype.toString.call(obj).slice(8, -1);
}

function getNode(wxRef = uni, selector, isAll = false) { //获取节点信息
	let str = isAll ? "selectAll" : 'select';
	return new Promise((resolve, reject) => {
		wxRef.createSelectorQuery()[str](selector).boundingClientRect((res) => {
			if (res) {
				resolve(res);
			} else {
				reject("找不到该节点--" + selector);
			}
		}).exec();
	})
}

function randomNum(minNum, maxNum, isId) { //生成随机数,区间为[minNum,maxNum]
	minNum = Math.floor(minNum);
	maxNum = Math.floor(maxNum);
	switch (arguments.length) {
		case 1:
			maxNum = minNum;
			minNum = 0;
		case 2:
			if (maxNum < minNum)[minNum, maxNum] = [maxNum, minNum];
			return parseInt(Math.random() * (maxNum - minNum + 1) + minNum, 10);
		default:
			return 0;
	}
}

function createID(params) {
	return new Date().getTime() + randomNum(0, 999).toString().padStart(3, '0')
}

function isParentNodeEl(obj, parentObj) { //判断dom子节点
	while (obj != undefined && obj != null && obj.tagName?.toUpperCase() != 'BODY') {
		if (obj == parentObj) {
			return true;
		};
		obj = obj.parentNode;
	};
	return false;
}

function getCursortPosition(ctrl) { //获取光标位置
	//获取光标位置函数 
	var CaretPos = 0;
	// IE Support
	if (document.selection) {
		ctrl.focus(); // 获取焦点
		var Sel = document.selection.createRange(); // 创建选定区域
		Sel.moveStart('character', -ctrl.value.length); // 移动开始点到最左边位置
		CaretPos = Sel.text.length; // 获取当前选定区的文本内容长度
	}
	// Firefox support 
	else if (ctrl.selectionStart || ctrl.selectionStart == '0') {
		CaretPos = ctrl.selectionStart; // 获取选定区的开始点 
	};
	return CaretPos;
}


function setCaretPosition(ctrl, pos) { //设置光标位置
	console.log({
		ctrl,
		pos
	});
	//设置光标位置函数 
	if (ctrl.setSelectionRange) {
		ctrl.focus(); // 获取焦点
		ctrl.setSelectionRange(pos, pos); //设置选定区的开始和结束点
	} else if (ctrl.createTextRange) {

		var range = ctrl.createTextRange(); // 创建选定区
		range.collapse(true); // 设置为折叠,即光标起点和结束点重叠在一起
		range.moveEnd('character', pos); // 移动结束点
		range.moveStart('character', pos); // 移动开始点
		range.select(); // 选定当前区域
	}
}

function uint8ArrayToString(utf8EncodedData, codeType = "UTF-8") { //Uint8Array 转 字符串
	// console.log("uint8ArrayToString");
	// console.log({ utf8EncodedData, codeType });
	// 常见的编码格式有ASCII、ANSI、GBK、GB2312、UTF-8、GB18030和UNICODE等
	return (new TextDecoder(codeType)).decode(utf8EncodedData);
}

function stringToUint8Array(str) { //字符串 转 Uint8Array
	return (new TextEncoder()).encode(str);
}

function isCollision_rect(rect1, rect2) { //判断两个矩形是否碰撞
	let {
		offsetHeight,
		offsetLeft,
		offsetTop,
		offsetWidth
	} = rect1;
	let px1 = rect2.offsetLeft;
	let px2 = rect2.offsetLeft + rect2.offsetWidth;
	let py1 = rect2.offsetTop;
	let py2 = rect2.offsetTop + rect2.offsetHeight;
	let minX = (px1 - px2) > 0 ? px2 : px1;
	let maxX = (px1 - px2) > 0 ? px1 : px2;
	let minY = (py1 - py2) > 0 ? py2 : py1;
	let maxY = (py1 - py2) > 0 ? py1 : py2;

	let arr = [{
			x: offsetLeft,
			y: offsetTop
		},
		{
			x: offsetLeft + offsetWidth,
			y: offsetTop
		},
		{
			x: offsetLeft + offsetWidth,
			y: offsetTop + offsetHeight
		},
		{
			x: offsetLeft,
			y: offsetTop + offsetHeight
		},
		// { x: offsetLeft + offsetWidth / 2, y: offsetTop + offsetHeight / 2 },
		{
			x: offsetLeft + offsetWidth / 2,
			y: offsetTop
		},
		{
			x: offsetLeft + offsetWidth,
			y: offsetTop + offsetHeight / 2
		},
		{
			x: offsetLeft + offsetWidth / 2,
			y: offsetTop + offsetHeight
		},
		{
			x: offsetLeft,
			y: offsetTop + offsetHeight / 2
		},
	];

	let condition1 = arr.some(({
		x,
		y
	}) => x >= minX && x <= maxX && y >= minY && y <= maxY);
	let condition2 = (offsetLeft >= minX) && (offsetLeft + offsetWidth <= maxX) && (offsetTop <= minY) && (offsetTop +
		offsetHeight >= maxY);
	let condition3 = (offsetLeft <= minX) && (offsetLeft + offsetWidth >= maxX) && (offsetTop >= minY) && (offsetTop +
		offsetHeight <= maxY);
	return condition1 || condition2 || condition3;
}

function getElementCoordinateOfscene(element, arr = ['offsetLeft', 'offsetTop']) { //在视图获取元素坐标
	let returnVal = [];
	arr.map(e => {
		var param = element[e]; //这是获取元素距父元素顶部的距离
		var current = element.offsetParent; //这是获取父元素
		while (param != undefined && current != undefined && current != null) { //当它上面有元素时就继续执行
			param += current[e]; //这是获取父元素距它的父元素顶部的距离累加起来
			current = current.offsetParent; //继续找父元素
		};
		returnVal.push({
			[e]: param
		});
	});
	return returnVal;
}

function deepClone(obj) { //深拷贝
	let objClone = Array.isArray(obj) ? [] : {};
	if (obj && typeof obj === "object") {
		for (var key in obj) {
			if (obj.hasOwnProperty(key)) {
				//判断ojb子元素是否为对象，如果是，递归复制
				if (obj[key] && typeof obj[key] === "object") {
					objClone[key] = deepClone(obj[key]);
				} else {
					//如果不是，简单复制
					objClone[key] = obj[key];
				}
			}
		}
	}
	return objClone;
};

function deepProxySet(obj, cb = function() {}) { //Proxy对象set深监听
	let condition = ["Function", "Object", "Array"].includes(myTypeOf(obj));
	let handler = {
		set(t, p, n, s) {
			t[p] = condition ? deepProxySet(n, cb) : n;
			cb(t, p, n, s);
			return true;
		}
	};

	if (!condition) return obj;
	else {
		for (let key in obj) {
			if (condition) obj[key] = deepProxySet(obj[key], cb);
		};
	};

	return new Proxy(obj, handler);
}

function myCreateElement(field, tagName) { //创建dom元素并添加类名
	let dom = {};
	dom[field] = document.createElement(tagName);
	dom[field].classList.add(field);
	return dom[field];
}

function dycalendar(dateStr, format) { //创建日历数据 dateStr=>"YYYY-MM-DD"
	let head = `一二三四五六日`.split("");
	let date = new Date(dateStr);
	let currMonth = date.getMonth() + 1;
	date.setDate(1);
	let currDay = date.getDate();
	let year = date.getFullYear();
	let currWeek = date.getDay();
	currWeek = currWeek ? currWeek : 7;

	// 1,3,5,7,8,10,12 这几月永远31天。2月平年28天，闰年（一般年份能整除4或百年年份能整除400的是闰年，）29天，其他月份30天。
	let isrun = (year % 4 == 0 && year % 100 != 0) || year % 400 == 0;
	let dayNum = 0;
	if ([1, 3, 5, 7, 8, 10, 12].includes(currMonth)) {
		dayNum = 31;
	} else if (currMonth == 2) {
		dayNum = isrun ? 29 : 28;
	} else {
		dayNum = 30;
	};
	let prevMonth = new Date(new Date(dateStr).setDate(0));
	let prevMonthLastDay = prevMonth.getDate();

	let content = [];
	let content2 = [];
	let next = {};
	for (let i = 0; i < 6; i++) { // 共六行
		let temp = [];
		let temp2 = [];
		for (let j = 0; j < 7; j++) { // 共七天
			let day = 0;
			let dateVal = '';

			if (1 + j + i * 7 - currWeek == dayNum) { // 下个月1号的坐标位置
				next.i = i;
				next.j = j;
			};
			if (i == 0 && j < currWeek - 1) { // 第一行，上个月的日期
				day = prevMonthLastDay + j - currWeek + 2;
				dateVal =
					`${prevMonth.getFullYear()}-${String(prevMonth.getMonth() + 1).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
			} else if (i == 0 && j >= currWeek - 1) { // 第一行，当月1号之后的日期
				day = 2 + j - currWeek;
				dateVal = `${year}-${String(currMonth).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
			} else if (i != 0 && 1 + j + i * 7 - (currWeek - 1) <= dayNum) { // 第二行开始，当月的日期
				day = 2 + j + i * 7 - currWeek;
				dateVal = `${year}-${String(currMonth).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
			} else { // 下个月的日期
				day = 1 + j - next.j + (i - next.i) * 7;
				let nextMonth = new Date(dateStr);
				nextMonth.setMonth(currMonth);
				dateVal =
					`${nextMonth.getFullYear()}-${String(nextMonth.getMonth() + 1).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
			};
			temp.push(day);
			temp2.push(dateVal);
		}
		content.push(temp);
		content2.push(temp2);
	};
	switch (format) {
		case 'thead':
			return {
				head, content
			};
		case 'all':
			return {
				head, content, currWeek, currMonth, currDay, year, content2
			};
		default:
			return content;
	};
}

function changeDate([date = new Date(), fnName = '', isCopy = false]) { //修改Date对象
	if (isCopy) date = new Date(date);
	if (myTypeOf(date[fnName]) == 'Function') date[fnName](...[].slice.call(arguments, 1));
	return date;
}

function changeData([data, fnName = '', isCopy = false, customCopy]) { //修改对象
	if (isCopy) data = (myTypeOf(customCopy) == 'Function') ? customCopy(data) : JSON.parse(JSON.stringify(data));
	if (myTypeOf(data[fnName]) == 'Function') data[fnName](...[].slice.call(arguments, 1));
	return data;
}

function setVideoSrc(el) { // 获取视频时长
	// 时长转换
	function durationTrans(a) {
		var b = ""
		var h = parseInt(a / 3600),
			m = parseInt(a % 3600 / 60),
			s = parseInt(a % 3600 % 60);
		if (h > 0) {
			h = h < 10 ? '0' + h : h
			b += h + ":"
		}
		m = m < 10 ? '0' + m : m
		s = s < 10 ? '0' + s : s
		b += m + ":" + s
		return b;
	}

	var url = '';
	if (typeof el == "string") {
		url = el;
	} else {
		//获取视频对象
		var content = el.files[0]
		console.log(content)
		//获取音频、视频时长
		url = URL.createObjectURL(content);
	};
	var audioElement = new Audio(url);
	audioElement.volume = 0;
	audioElement.play();
	// audioElement.addEventListener("play", function() {
	// 	console.log("play", audioElement.duration);
	// })
	// audioElement.addEventListener("playing", function() {
	// 	console.log("playing", audioElement.duration);
	// })
	// audioElement.addEventListener("durationchange", function(_event) {
	// 	console.log('audioElement.duration——durationchange', audioElement.duration);
	// })
	var duration;
	return new Promise((resolve, reject) => {
		audioElement.addEventListener("loadedmetadata", function(_event) {
			duration = audioElement.duration;
			audioElement.pause()
			// console.log(duration + 's');
			// console.log(durationTrans(duration))
			resolve(duration);
		});
	});
}

function seconds2time(index_num) { //秒数转时间
	let getHours = (parseInt(index_num / 60 / 60) % 12).toString().padStart(2, 0);
	let getMinutes = (parseInt(index_num / 60) % 60).toString().padStart(2, 0);
	let getSeconds = ((index_num) % 60).toFixed(2);
	if (getSeconds < 10) getSeconds = '0' + getSeconds;
	// let str = `${getHours}.${getMinutes}.${getSeconds}`;
	let str = `${getHours}:${getMinutes}:${getSeconds}`;
	return str;
}

/**
 * 数字金额大写转换(可以处理整数,小数,负数)
 * @param 
 **/
function digitUppercase(n) {
	var fraction = ['角', '分'];
	var digit = [
		'零', '壹', '贰', '叁', '肆',
		'伍', '陆', '柒', '捌', '玖'
	];
	var unit = [
		['元', '万', '亿'],
		['', '拾', '佰', '仟']
	];
	var head = n < 0 ? '欠' : '';
	n = Math.abs(n);
	var s = '';
	for (var i = 0; i < fraction.length; i++) {
		s += (digit[Math.floor(n * 10 * Math.pow(10, i)) % 10] + fraction[i]).replace(/零./, '');
	}
	s = s || '整';
	n = Math.floor(n);
	for (var i = 0; i < unit[0].length && n > 0; i++) {
		var p = '';
		for (var j = 0; j < unit[1].length && n > 0; j++) {
			p = digit[n % 10] + unit[1][j] + p;
			n = Math.floor(n / 10);
		}
		s = p.replace(/(零.)*零$/, '').replace(/^$/, '零') + unit[0][i] + s;
	}
	return head + s.replace(/(零.)*零元/, '元')
		.replace(/(零.)+/g, '零')
		.replace(/^整$/, '零元整');
};

function simulateKey() { //模拟按键
	console.log('模拟按下 F11 键');
	// 模拟按下 F11 键
	const keyDownEvent = new KeyboardEvent('keydown', {
		key: 'F11',
		keyCode: 122, // F11 键的 keyCode
		which: 122 // F11 键的 which 值
	});

	window.dispatchEvent(keyDownEvent);

	// 模拟释放 F11 键
	const keyUpEvent = new KeyboardEvent('keyup', {
		key: 'F11',
		keyCode: 122,
		which: 122
	});

	window.dispatchEvent(keyUpEvent);
}

function fullScreen() { //实现全屏
	var de = document.documentElement;
	if (!document.fullscreenElement) {
		if (de.requestFullscreen) {
			de.requestFullscreen();
		} else if (de.mozRequestFullScreen) {
			de.mozRequestFullScreen();
		} else if (de.webkitRequestFullScreen) {
			de.webkitRequestFullScreen();
		};
	};
}

function exitFullscreen() { //退出全屏
	if (document.fullscreenElement) {
		if (document.exitFullscreen) {
			document.exitFullscreen();
		} else if (document.mozCancelFullScreen) {
			document.mozCancelFullScreen();
		} else if (document.webkitExitFullscreen) {
			document.webkitExitFullscreen();
		};
	};
}

function arr2MdArr(arr = [], ...args) { //数组转二维数组
	if (args.length == 0) return arr;
	arr = JSON.parse(JSON.stringify(arr));
	let returnVal = [];
	let prevArg = 0;
	[...args].map(arg => {
		if (arg > 0) {
			returnVal.push(arr.slice(prevArg, prevArg + arg));
			prevArg += arg;
		};
	});
	returnVal.push(arr.slice(prevArg));
	return returnVal;
};

function getMaxInd(lengthValList = []) { //获取一组数据最大值的索引
	return lengthValList.indexOf(Math.max(...lengthValList))
}

function calculateStrSimilarity(str1, str2) { //计算相似性
	// 将字符串转换为字符数组
	const arr1 = [...str1];
	const arr2 = [...str2];
	console.log({
		arr1,
		arr2
	});
}

function copy(textToCopy) {
	// 创建一个临时的文本输入框
	var tempInput = document.createElement("input");
	tempInput.value = textToCopy;
	tempInput.style.display = 'none';
	document.body.appendChild(tempInput);

	// 选择文本
	tempInput.select();

	// 复制文本到剪贴板
	// document.execCommand("copy");
	navigator.clipboard.writeText(textToCopy);

	// 移除临时输入框
	document.body.removeChild(tempInput);
}

async function customFetch(url, method = 'GET', data = null, headers = {}, cb) {
	let type = (tools.myTypeOf(data));
	// 创建一个对象来配置Fetch请求
	const token = localStorage.getItem('token') || null;
	const options = {
		method,
		headers: {
			'Content-Type': 'application/json', // 根据需要设置请求头
			'Authorization': token,
			...headers
		},
	};
	if (method === 'GET' && data) {
		// 如果是GET请求且有查询参数，将其添加到URL中
		const queryParams = new URLSearchParams(data);
		url += `?${queryParams.toString()}`;
	} else if (data) {
		switch (options.headers['Content-Type']) {
			case 'application/json': //请求数据为json格式
				options.body = JSON.stringify(data);
				break;
			case 'application/x-www-form-urlencoded': //请求数据为表单格式
				options.body = new URLSearchParams(data);
				break;
			case 'multipart/form-data': //请求数据为FormData对象
			default:
				delete options.headers;
				let formData = new FormData();
				if (type == 'FormData') {
					formData = data;
				} else if (type == 'Object') {
					for (const key in data) {
						formData.append(key, data[key]);
					};
				};
				options.body = formData;
				break;
		};
	};

	// 发起Fetch请求并返回Promise
	try {
		const response = await fetch(url, options);
		if (!response.ok) {
			throw new Error('网络请求失败');
		};
		let res = await response.json();
		let data_1 = null;
		if (myTypeOf(cb) == 'Function') {
			data_1 = cb(res);
		} else {
			if (res.code == '10200') {
				data_1 = res;
			} else if (res.code == '10005') {

			} else {
				window.alert(res.message);
			};
		};
		return await data_1;
	} catch (error) {
		console.error('发生错误:', error);
		throw error;
	};
};

function base64toBlob(dataurl) { //base64转Blob
	var arr = dataurl.split(','),
		mime = arr[0].match(/:(.*?);/)[1],
		bstr = atob(arr[1]),
		n = bstr.length,
		u8arr = new Uint8Array(n);
	while (n--) {
		u8arr[n] = bstr.charCodeAt(n);
	}
	return new Blob([u8arr], {
		type: mime
	});
}

function loadFont(_fontName, _fontUrl) { // 字体加载
	return new Promise((resolve, reject) => {
		// let reg = new RegExp('\\b' + _fontName + '\\b')

		// let _fontFamily = document.body.style.fontFamily

		// if (reg.test(_fontFamily)) {
		//   return
		// }

		// if (checkFont(_fontName)) {
		// 	console.log('已有字体：', _fontName)
		// 	resolve(true);
		// 	return
		// }


		let prefont = new FontFace(
			_fontName,
			'url(' + _fontUrl + ')'
		);

		prefont.load().then(function(loaded_face) {
			document.fonts.add(loaded_face);
			// document.body.style.fontFamily = (_fontFamily ? _fontFamily + ',' : _fontFamily) + _fontName;

			// console.log('字体加载成功', loaded_face, document.fonts)
			resolve(true);
		}).catch(function(error) {
			// console.log('字体加载失败', error)
			resolve(false);
		});
	});
}

function loadFont_wx(_fontName, _fontUrl) { // 字体加载
	return new Promise((resolve, reject) => {
		uni.loadFontFace({
			family: _fontName,
			source: `url("${_fontUrl}")`,
			global: true,
			success(res) {
				resolve(true);
			},
			fail(err) {
				resolve(false);
			}
		})
	})
}

function loadImageWhenIdle(url, callback = img => {}) { // 使用requestIdleCallback在浏览器空闲时加载图片
	// 定义图片加载函数
	function loadImage(url, callback) {
		const img = new Image();
		img.onload = function() {
			callback(img);
		};
		img.onerror = function() {
			console.error('图片加载失败:', url);
		};
		img.src = url;
	}

	if ('requestIdleCallback' in window) {
		window.requestIdleCallback(function(deadline) {
			if (deadline.timeRemaining() > 0) {
				loadImage(url, callback);
			} else {
				// 时间已经耗尽，重试下一个空闲时段
				loadImageWhenIdle(url);
			}
		});
	} else {
		// 浏览器不支持requestIdleCallback，直接加载
		loadImage(url, callback);
	}
}


// 获取URL参数
function getQueryParam(param) {
	const url = window.location.href;
	const queryString = url.substring(url.indexOf('?') + 1);
	const params = queryString.split('&');
	const obj = {};
	params.map(e => {
		const prop = e.split('=');
		obj[prop[0]] = prop[1] || '';
	});
	// console.log(params, obj)
	return obj[param]
}

export let tools = {
	imgPath: "",
	companyName: "言影",
	vadIp: "47.106.224.147",
	merchantId: "",
	wxAppid: "",
	getQueryParam,
	loadImageWhenIdle,
	loadFont,
	loadFont_wx,
	base64toBlob,
	customFetch,
	getMaxInd,
	arr2MdArr,
	fullScreen,
	exitFullscreen,
	simulateKey,
	isRGBFormat,
	isHexFormat,
	rgbToHex,
	hexToRgb,
	getRGBAValue,
	digitUppercase,
	seconds2time,
	setVideoSrc,
	changeDate,
	changeData,
	isCollision_rect,
	styleObj2Str,
	formatTime,
	formatDate,
	formatNumber,
	Adapt,
	copy,
	getAge,
	num2weekDay,
	getDateToNewData,
	getAstro,
	easyToast,
	throttle,
	debounce,
	urlEncode,
	deCodeUrl,
	rpx2px,
	px2rpx,
	vh2px,
	editStr,
	myTypeOf,
	deepProxySet,
	deepClone,
	getNode,
	randomNum,
	createID,
	isParentNodeEl,
	getCursortPosition,
	setCaretPosition,
	uint8ArrayToString,
	stringToUint8Array,
	myCreateElement,
	dycalendar,
	getElementCoordinateOfscene,
	calculateStrSimilarity
};

import urlJson from "./url.json";
tools.urlJson = urlJson;


// #ifdef APP
import permision from "@/utils/app_permission.js";
tools.app_permision = permision;
tools.currUrl = urlJson.currUrl;
let currWebItem = urlJson.list.find(e => {
	if (e.tips == '弃用') return false;
	return e.url == urlJson.currUrl;
})
if (currWebItem?.sub && currWebItem.sub.length != 0) {
	tools.merchantId = urlJson.currMerchantId;
} else {
	tools.merchantId = "";
}
// #endif


// #ifdef H5
switch (window.location.host) {
	case 'smarts.lsjz-ai.com':
		tools.currUrl = "ai.lsjz-ai.com";
		tools.merchantId = getQueryParam("merchantId") || getQueryParam("MerchantId") || "m10001";
		break;
	default:
		tools.currUrl = urlJson.currUrl;
		tools.merchantId = urlJson.currMerchantId;
		break;
}
// #endif


// #ifndef MP
tools.imgPath = '/static/assets/';
urlJson.list.some(e => {
	if (e.tips == '弃用') return false;
	if (e.url == tools.currUrl) {
		console.log(e.url, tools.currUrl, e.companyName)
		if (tools.merchantId && e.sub && e.sub.length != 0) {
			return e.sub.some(subItem => {
				if (subItem.tips == '弃用') return false;
				if (subItem.merchantId == tools.merchantId) {
					tools.vadIp = subItem.vadIp;
					tools.companyName = subItem.companyName || '言影';
					tools.appName = subItem.name;
					return true
				}
			});
		} else {
			tools.vadIp = e.vadIp;
			tools.companyName = e.companyName || '言影';
			tools.appName = e.name;
			return true;
		}
	}
})
// #endif

// #ifdef MP
tools.imgPath = 'https://h5.yainoo.com/static/assets/';
// tools.imgPath = 'http://localhost:8080/static/assets/';
// tools.imgPath = ' http://192.168.124.87:8080/static/assets/';

const accountInfo = uni.getAccountInfoSync();
tools.wxAppid = accountInfo.miniProgram.appId;
switch (tools.wxAppid) {
	case 'wxbdd94a982a742f5b':
		tools.companyName = "言影";
		tools.vadIp = "47.106.224.147";
		break;
	case 'wx20be0b577e748a8e':
		tools.companyName = "随拍";
		// tools.vadIp = "47.121.176.211";
		tools.vadIp = "47.121.201.224";
		break;
	case 'wxa71b495f0fa978da':
		tools.companyName = "默客";
		tools.vadIp = "47.121.185.165";
		break;
	case 'wx4e87e64f5d13e52c':
		tools.companyName = "极智拍";
		tools.vadIp = "121.196.245.10";
		// tools.merchantId = '';
		tools.merchantId = 'm10001';
		break;
	default:
		break;
}
// #endif



let contList = [{
		text: '你就是这样，酷到要死，倔强到要死，敏感到要死，遇到事只会死撑，眼里容不下一粒沙子，所以没有一个真正喜欢你的人，也没有人在乎你的感受。'
	},
	{
		text: '你没权利看不惯我的生活方式，但你有权抠瞎自己的双眼。把闲言碎语留给市井小人，你只管优雅从容心怀远方'
	},
	{
		text: '我觉得其实很难碰到一个人，就是让你心动、喜欢，并且是挺合适的一个人。所以我只是劝现在年轻人，不要轻易地去放开另一半的手。有时候我们去坚持一下，也许两个人慢慢地就会变得越来越好了'
	},
	{
		text: '哭的时候没人哄，学会了坚强；怕的时候没人陪，学会了勇敢；烦的时候没人问，学会了承受；累的时候没人依靠，学会了自立。一个人，如果不坚强，软弱给谁看'
	},
	{
		text: '每一句“我不怕”的背后都是恐慌，每一句“我很好”的背后都是不好，每一句“我可以”的背后都是硬着头皮'
	},
	{
		text: '有时候应该适当的有点脾气，对待有些人真不能太温柔和忍耐，因过分善良会让你丢失自己的价值和尊严。过分善良，也是一种傻'
	},
	{
		text: '真正的内心强大，就是活在自己的世界里，而不是活在别人的眼中和嘴上。为人处事靠自己，背后评说由他人'
	},
	{
		text: '人活着就是为了解决困难，这才是生命的意义，也是生命的内容。逃避不是办法，知难而上往往是解决问题的最好手段'
	},
	{
		text: '有些时候感觉心里冷冷清清，有些人请不进来，有些人不让进来。有时我可以看得很淡然，有时我却执着得有些不堪'
	},
	{
		text: '自己喜欢的东西就不要问别人好不好看，自己决定做的事就不要问别人同不同意，你的生活不会因为别人的话而变好，但会因为你的努力而有更多可能性'
	},
	{
		text: '时间在走，年龄在长。懂得的多了，看透的多了，快乐越来越少了。我怀念，那些年，未来遥远的没有形状，我们单纯得没有烦恼'
	},
	{
		text: '喜欢就百分之百的投入和温柔，离开的时候就摆摆手，大步向前走，那个爱的洒脱又利落的你，不知道有多酷'
	},
	{
		text: '遇见了形形色色的人之后，你才知道，原来世界上除了父母不会有人掏心掏肺对你，不会有人无条件完全信任你，也不会有人一直对你好，你早该明白，天会黑、人会变，人生那么长路那么远，你只能靠自己，别无他选。'
	},
	{
		text: '我为什么会喜欢你，这个问题我问了自己很多遍，我不知道答案，我只知道，你在我我便安心，你不在，我便忧心。'
	},
	{
		text: '其实，没有什么东西是不能放手的。时日渐远，当你回望，你会发现，你曾经以为不可以放手东西，只是生命里的一块跳板，令你成长。'
	},
	{
		text: '当你看清了一个人而不揭穿，你就懂得了原谅的意义；讨厌一个人而不翻脸，你就懂得了至极的尊重。活着，总有你看不惯的人，也有看不惯你的人。'
	},
	{
		text: '一杯敬朝阳，一杯敬月光。唤醒我的向往，温柔了寒窗。于是可以不回头的逆风飞翔，不怕心头有雨，眼底有霜。'
	},
	{
		text: '别轻易就认为谁是你的世界，也别轻易就付出所有，别吵着说回忆多汹涌，静下来你会发现，很多人最后的关系，就是没有关系。'
	},
	{
		text: '有一个夜晚我烧毁了所有的记忆，从此我的梦就透明了；有一个早晨我扔掉了所有的昨天，从此我的脚步就轻盈了。'
	},
	{
		text: '没有人能烦恼你，除非你拿别人的言行来烦恼自己。人这辈子，简简单单就是幸福，无病无灾就是顺利，平平淡淡就是真谛。'
	},
	{
		text: '从此，我的幸福与你无关，原来世界上真的没有什么是永远。一段友情，离开了就淡了。一段爱情，分离了就散了。现在所拥有的，也许下一秒，就不再属于你。'
	},
	{
		text: '年轻的时候，连多愁善感都要渲染的惊天动地。长大后却学会，越痛，越不动声色。越苦，越保持沉默。成长就是将你的哭声调成静音模式。'
	},
	{
		text: '我想努力拼未来，以后赚很多的钱，不是因为我爱钱，而是这辈子我不想因为钱和谁在一起，也不想因为钱而离开谁。'
	},
	{
		text: '曾经以为，伤心是会流很多眼泪的，原来，真正的伤心，是流不出一滴眼泪。什么事情都会过去，我们是这样活过来的。'
	},
	{
		text: '不要去听别人的忽悠，你人生的每一步都必须靠自己的能力完成。自己肚子里没有料，手上没本事，认识再多人也没用。'
	},
	{
		text: '不想回的消息就不回，讨厌的人就离远一点，不开心就表现出来，不要总活在看别人脸色的生活中，得早一点变酷，可爱不是长久之计。'
	},
	{
		text: '先别急着爱我，如果你愿意，先来尝尝我的怪脾气和自私、任性、口是心非，过后，若你还爱我，那我的世界就只有你。'
	},
	{
		text: '生活总是让我们遍体鳞伤，但请相信，你今天受的苦，吃的亏，担的责，扛的罪，忍的痛，到最后都会变成光，照亮你的路。'
	},
	{
		text: '锦上添花人人都会，难的是雪中送炭；短暂热情人人都有，难的是长久相守。陪你走过困苦的人，最深情；与你历经风雨的人，最真诚。真爱无需语言，行动总能体现；深情无需表白，时间总会见证。'
	},
]
tools.contList = contList;

try {
	if(exports){
		exports.tools = tools;
	}
} catch (error) {
	
}

// export default tools;
// AOP通用函数
// Function.prototype.after = function (afterfn) {
// 	var _self = this;
// 	return function () {
// 		var ret = _self.apply(this, arguments);
// 		afterfn.apply(this, arguments);
// 		return ret;
// 	}
// }